"use client";
import React, { useEffect, useState } from "react";
import type { MenuProps } from "antd";
import {
  Layout,
  theme,
  Tabs,
  Select,
  Form,
  DatePicker,
  Button,
  Table,
  Space,
  Modal,
  Popconfirm,
} from "antd";
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons";
import type { TableColumnsType, TableProps } from "antd";
import Modals from "@/app/[locale]/czy/modal";
import axios from "axios";
import dayjs from "dayjs";
type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];

interface DataType {
  id: number;
  name: string;
  khzt: string;
  khxj: number;
  lxr: string;
  phone: number;
  time: number;
  timefalse: number;
}
const onChange: TableProps<DataType>["onChange"] = (
  pagination,
  filters,
  sorter,
  extra
) => {
  console.log("params", pagination, filters, sorter, extra);
};

export default function Lsy() {
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        id: "odd",
        text: "",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: "客户名称",
      dataIndex: "name",
      width: 240,
      render: (name, record) => <a>{name}</a>,
    },
    {
      title: "客户状态",
      dataIndex: "khzt",
      width: 130,
      render: (khzt, record) => <a>{khzt}</a>,
    },
    {
      title: "客户星级",
      dataIndex: "khxj",
      width: 150,
      sorter: {
        compare: (a, b) => a.khxj - b.khxj,
        multiple: 2,
      },
      showSorterTooltip: false,
    },
    {
      title: "首联系人",
      dataIndex: "lxr",
      width: 120,
      render: (lxr, record) => <a>{lxr}</a>,
    },
    {
      title: "手机号码",
      dataIndex: "phone",
      width: 180,
      sorter: {
        compare: (a, b) => a.phone - b.phone,
        multiple: 1,
        showSorterTooltip: false,
      },
    },
    {
      title: "最后跟进",
      dataIndex: "time",
      width: 180,
      sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 1,
      },
      render: (data) => {
        return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
      },
      showSorterTooltip: false,
    },
    {
      title: "更进天数",
      dataIndex: "timefalse",
      width: 120,
      align: "center",
      sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 1,
      },
      showSorterTooltip: false,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <a>更进</a>
          <a
            onClick={() => {
              setTitle("编辑");
              showModal();
              setObjItem(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              let index = data.findIndex((item) => item.id == record.id);
              console.log(index, "/置顶的下标");

              data.splice(index, 1);
              // data.unshift(record);
              console.log(data, "/置顶后的数组");
              setDate([record, ...data]);
            }}
          >
            置顶
          </a>
          <Popconfirm
            title="删除提示"
            description="是否确定删除?"
            onConfirm={async () => {
              await axios.delete(
                `http://localhost:3000/datalist/${record.id}`,
                { headers: { "Content-Type": "application/json" } }
              );
              getDate();
            }}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [data, setDate] = useState([]);
  // 获取所有数据
  const getDate = async () => {
    let res = await axios
      .get("http://localhost:3000/datalist")
      .then((res) => res.data);
    setDate(res);
  };

  useEffect(() => {
    getDate();
  }, []);

  const [isModalOpen, setIsModalOpen] = useState(false);

  const [title, setTitle] = useState("添加");
  const [objItem, setObjItem] = useState({});

  const showModal = () => {
    setIsModalOpen(true);
  };

  // 编辑数据
  const handleOk = async (obj: any) => {
    setIsModalOpen(false);
    await axios.patch(`http://localhost:3000/datalist/${obj.id}`, obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };

  // 添加数据
  const handleCancel = async (obj: any) => {
    setIsModalOpen(false);
    await axios.post("http://localhost:3000/datalist", obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };

  const [keyword, setKeyword] = useState("");
  const [customerStatus, setCustomerStatus] = useState("");
  const [customerType, setCustomerType] = useState("");
  const [lastFollowUp, setLastFollowUp] = useState("");

  // 搜索事件
  const handleSearch = async () => {
    try {
      const response = await axios.get("http://localhost:3000/datalist", {
        params: {
          khzt_like: keyword != "" ? keyword : undefined,
          khxj: customerStatus != "" ? customerStatus : undefined,
          name: customerType != "" ? customerType : undefined,
          time: lastFollowUp != "" ? lastFollowUp : undefined,
        },
      });
      setDate(response.data);
      console.log(keyword);
    } catch (error) {
      console.error("搜索出错:", error);
    }
  };
  let [form] = Form.useForm();
  return (
      <div
        style={{
          width: "1400px",
          height: "720px",
          backgroundImage: "none",
          textAlign: "left",
          overflow: "auto",
        }}
      >
        {/* 头部tab标签 */}
        <div style={{ padding: "0px 10px" }}>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                label: "全部客户",
                key: "1",
                // children: '全部客户',
              },
              {
                label: "我的客户",
                key: "2",
                // children: '我的客户',
              },
              {
                label: "下属客户",
                key: "3",
                // children: '下属客户',
              },
              {
                label: "重点客户",
                key: "4",
                // children: '重点客户',
              },
              {
                label: "我协作的",
                key: "5",
                // children: '我协作的',
              },
              {
                label: "下属协作的",
                key: "6",
                // children: '下属协作的',
              },
            ]}
          />
        </div>
        {/* 搜索栏 */}
        <Form
          form={form}
          style={{
            display: "flex",
            backgroundColor: "white",
            width:'1400px'
          }}
        >
          <Form.Item name="name" style={{ width: "190px", marginLeft: "10px" ,lineHeight:'70px'}}>
            <Select
              placeholder="客户名称"
              onChange={(e) => setCustomerType(e)}
              options={[
                {
                  value: "深圳市腾讯计算机系统有限公司",
                  label: "深圳市腾讯计算机系统有限公司",
                },
                {
                  value: "深圳市亿恩科技有限公司",
                  label: "深圳市亿恩科技有限公司",
                },
              ]}
            />
          </Form.Item>
          <Form.Item name="khzt" style={{ width: "190px", marginLeft: "20px" ,lineHeight:'70px'}}>
            <Select
              placeholder="客户状态"
              onChange={(e) => setKeyword(e)}
              options={[
                { value: "已完成", label: "已完成" },
                { value: "未完成", label: "未完成" },
                { value: "待审核", label: "待审核" },
              ]}
            />
          </Form.Item>
          <Form.Item name="khxj" style={{ width: "190px", marginLeft: "20px" ,lineHeight:'70px'}} >
            <Select
              onChange={(e) => setCustomerStatus(e)}
              placeholder="客户星级"
              options={[
                { value: "1", label: "1" },
                { value: "2", label: "2" },
                { value: "3", label: "3" },
                { value: "4", label: "4" },
                { value: "5", label: "5" },
              ]}
            />
          </Form.Item>
          <Form.Item  style={{lineHeight:'70px'}}>
            <Button
            style={{ width: "100px", marginLeft: "20px" }}
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
          </Form.Item>
          <Form.Item style={{lineHeight:'70px'}}>
            <Button
             style={{ width: "100px", marginLeft: "20px" }}
              icon={<RedoOutlined />}
              onClick={() => {
                form.resetFields();
                getDate();
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>

        {/* 按钮 */}
        <div
          style={{
            backgroundColor: "white",
          }}
        >
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ marginRight: "10px" }}
            onClick={() => {
              setTitle("添加");
              showModal();
              setObjItem({});
            }}
          >
            添加
          </Button>
        </div>
        {/* 表格列表 */}

        <Table<DataType>
          rowSelection={rowSelection}
          rowKey='id'
          columns={columns}
          dataSource={data}
          onChange={onChange}
          pagination={{ defaultCurrent: 1, defaultPageSize: 6 }}
          showSorterTooltip={{ target: "sorter-icon" }}
        />

        <Modal
          title={title}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
        >
          <Modals
            title={title}
            onCancel={handleCancel}
            onOk={handleOk}
            objItem={objItem}
            key={new Date().getTime()}
          />
        </Modal>
      </div>
  );
}
